package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import modelos.Concessionaria;

public class DAOConcessionaria 
{
	Connection connection = null;
	PreparedStatement comando = null;
	ResultSet result = null;
	
	public DAOConcessionaria()
	{
		connection = ConnectionFactory.createConnection();
	}
	
	public void insereConcessionaria(String razaoSocial, String cnpj, String login, String senha) throws SQLException
	{
		comando = connection.prepareStatement("INSERT INTO concessionarias (razao_social, cnpj, login, senha) VALUES (?,?,?,?)");
		
		comando.setString(1, razaoSocial);
		comando.setString(2, cnpj);
		comando.setString(3, login);
		comando.setString(4, senha);
		
		comando.execute();
		
		this.fechaConexao(connection);
	}
	
	public List<Concessionaria> buscaConcessionarias() throws SQLException
	{
		List<Concessionaria> concessionarias = new ArrayList<Concessionaria>();
		Concessionaria conc = null;
		
		comando = connection.prepareStatement("SELECT * FROM concessionarias");
		
		result = comando.executeQuery();
		
		while(result.next())
		{
			conc = new Concessionaria();
			
			conc.setRazaoSocial(result.getString("razao_social"));
			conc.setCnpj(result.getString("cnpj"));
			conc.setId(result.getInt("id"));
			conc.setLogin(result.getString("login"));
			conc.setSenha(result.getString("senha"));
			
			concessionarias.add(conc);
		}
		
		this.fechaConexao(connection);
		
		return concessionarias;
	}
	
	public void alteraConcessionaria(int id, String razaoSocial, String cnpj, String login, String senha) throws SQLException
	{
		comando = connection.prepareStatement("UPDATE concessionaria SET razao_social = ?, cnpj = ?, login = ?, senha = ? WHERE id = ?");
		
		comando.setString(1, razaoSocial);
		comando.setString(2, cnpj);
		comando.setString(3, login);
		comando.setString(4, senha);
		
		comando.execute();
		
		this.fechaConexao(connection);
	}
	
	public void excluiConcessionaria(int id) throws SQLException
	{
		comando = connection.prepareStatement("DELETE FROM concessionarias WHERE id = ?");
		
		comando.setInt(1, id);
		
		comando.execute();
		
		this.fechaConexao(connection);
	}
	
	public void fechaConexao(Connection conn) throws SQLException
	{
		conn.close();
	}
}
